#include "http.h"
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QVariantMap>
Http::Http(QObject *parent) :
    QObject(parent)
{
    manager = new QNetworkAccessManager;
    request = new QNetworkRequest;
    srcMsg = "";
    dstMsg = "";
    dstMeansList.clear();
    phMsg = "";
}

Http::~Http()
{
    delete manager;
    delete request;
}

void Http::setApiKey(const QString &apiKey)
{
    myApiKey = apiKey;
}

void Http::setUrl(const QString &url)
{
    this->url = url;
}

void Http::setApiType(Http::ApiTipe type)
{
    flagApiType = type;
}
//传入要翻译的子串 后两个子串默认均为 "auto"
void Http::setRequest(const QString &src, const QString from, const QString to)
{
    srcMsg = src;
    switch (flagApiType) {
    case ApiNow: //即时翻译
        url += QString("?query=%1&from=%2&to=%3").arg(srcMsg, from, to);
        request->setUrl(QUrl(url));
        request->setRawHeader("apikey", myApiKey.toLatin1());   //添加apiKey
        break;
    case ApiBaidu:  //百度翻译
        url += QString("?client_id=%1&q=%2&from=%3&to=%4").arg(myApiKey, srcMsg, from, to);
        request->setUrl(QUrl(url));
        break;
    case ApiWordBadu: //百度词典
        url += QString("?client_id=%1&q=%2&from=%3&to=%4").arg(myApiKey, srcMsg, from, to);
        request->setUrl(QUrl(url));
        break;
    }
    reply = manager->get(*request); //使用 get 方法请求
    connect(reply, SIGNAL(readyRead()), this, SLOT(processData())); //连接 应答的有数据可读信号 - 处理数据方法
}

//处理返回的数据. 若函数返回后, dstMsg为空, 查询失败
void Http::processData()
{
    QByteArray str = reply->readAll();  //读取应答
    switch (flagApiType) {
    case ApiNow:
        parseNowApi(str);
        break;
    case ApiBaidu:
        parseBaiduApi(str);
        break;
    case ApiWordBadu:
        preseBaiduWordApi(str);
        break;
    }
    qDebug() << str;
}
/* {
    "errNum": 0,
    "errMsg": "success",
    "retData": {
        "from": "en",
        "to": "zh",
        "trans_result": [
            {
                "src": "hello World",
                "dst": "你好世界"
            }
        ]
    }
} */
//解析 即时翻译 返回的 JSON 字段
void Http::parseNowApi(QByteArray replyStr)
{
    dstMsg = "";    //清空
    QJsonParseError parseError;
    QJsonDocument document = QJsonDocument::fromJson(replyStr, &parseError); //生成树
    if (parseError.error == QJsonParseError::NoError) { //无错误
        if (document.isNull() || document.isEmpty()) {
            return ;
        }
        if (document.isObject()) {
            QVariantMap map1 = document.toVariant().toMap();
            if ((map1["errNum"].toInt() != 0) || (map1["errMsg"].toString() != "success")) { //查询失败
                qDebug() << QStringLiteral("查询失败, 错误号: ") << map1["errNum"].toInt();
                return ;
            }
            QVariantMap map2 = map1["retData"].toMap();
            QVariant tmp;
            foreach (tmp, map2["trans_result"].toList()) {
                 QVariantMap map3 = tmp.toMap();
                 srcMsg = map3["src"].toString();
                 dstMsg = map3["dst"].toString();
            }
            qDebug() << "SRC:" << srcMsg << "DEST" << dstMsg;
            emit sig_destMsg(dstMsg);
        }
    } else {
        return ;
    }
}
/* {    //成功
    "from": "en",
    "to": "zh",
    "trans_result": [
        {
            "src": "today",
            "dst": "今天"
        },
        {
            "src": "tomorrow",
            "dst": "明天"
        }
    ]
}
{   //失败
    "error_code": "52001",
    "error_msg": "TIMEOUT",
    "from": "auto",
    "to": "auto",
    "query": "he's"
} */
void Http::parseBaiduApi(QByteArray replyStr)
{
    dstMsg = "";    //清空
    QJsonParseError parseError;
    QJsonDocument document = QJsonDocument::fromJson(replyStr, &parseError); //生成树
    if (parseError.error == QJsonParseError::NoError) { //无错误
        if (document.isNull() || document.isEmpty()) {
            return ;
        }
        if (document.isObject()) {
            QVariantMap map1 = document.toVariant().toMap();
            QVariantMap::const_iterator i = map1.find("error_code");    //检查是否查询失败
            if (i != map1.constEnd()) {
                qDebug() << QStringLiteral("查询失败, 错误号: ") << map1["error_code"].toInt() << map1["error_msg"].toString();
                dstMsg = QString("<Error> 错误号: %1 错误原因:%2 ").arg(map1["error_code"].toInt()).arg(map1["error_msg"].toString());
                emit sig_destMsg(dstMsg);
                return ;
            }
            QVariant tmp;
            foreach (tmp, map1["trans_result"].toList()) {
                QVariantMap map2 = tmp.toMap();
                dstMsg += QString("%1\n").arg(map2["dst"].toString());
            }
            qDebug() << "SRC:" << srcMsg << "DEST" << dstMsg;
            emit sig_destMsg(dstMsg);
        }
    } else {
        return ;
    }
}
/*{
    errno:0,        //错误码 0为成功 其他为失败
    from:"en",
    to:"zh"
    data:
    {
        symbols:[
            0:{
                parts:[
                    0: {
                        means:[     //该词性下的含义
                            0:"（构成疑问句和否定句）",
                            1:"（代替动词）",
                            2:"（用于加强语气）"
                        ],
                        part:"aux."     //词性
                    },
                    1: {
                        means:[
                            0:"做",
                            1:"干",
                            2:"学习",
                            3:"研究"
                        ],
                        part:"vt.& vi."
                    },
                ],
                ph_am:"du",     //美式音标
                ph_en:"du:"     //英式音标
            }
        ],
        word_name:"do"  //请求的词语
    },
} */
void Http::preseBaiduWordApi(QByteArray replyStr)
{
    dstMeansList.clear();
    phMsg = "";
    int size = 0;   //用于统计本词条的词性个数
    QJsonParseError parseError;
    QJsonDocument document = QJsonDocument::fromJson(replyStr, &parseError); //生成树
    if (parseError.error == QJsonParseError::NoError) { //无错误
        if (document.isNull() || document.isEmpty()) {
            return ;
        }
        if (document.isObject()) {
            QVariantMap map1 = document.toVariant().toMap();
            if (map1["errno"].toInt() != 0) {
                dstMsg = QString("<Error> 错误号: %1").arg(map1["errno"].toInt());
                QList<QString> tmp;
                tmp << dstMsg;
                QString tmp1 = "";
                emit sig_destWordMsg(1, tmp, tmp1);
                return ;
            }
            QVariantMap map2 = map1["data"].toMap();
            QVariant tmp;
            foreach (tmp, map2["symbols"].toList()) {
                QVariantMap map3 = tmp.toMap();
                if (map3["ph_en"].toString() != "") {
                    phMsg += QString("英式:[%1] ").arg(map3["ph_en"].toString());
                }
                if (map3["ph_am"].toString() != "") {
                    phMsg += QString("美式:[%1] \n").arg(map3["ph_am"].toString());
                }
                QVariant tmp2;

                foreach (tmp2, map3["parts"].toList()) {
                   QVariantMap map4 = tmp2.toMap();
                   QString mean;
                   mean = map4["part"].toString();  //先把词性写入
                   size++;  //词性 数目++
                   QVariant tmp3;
                   foreach (tmp3, map4["means"].toList()) {
                      mean += QString(" %1;").arg(tmp3.toString());
                   }
                   mean += "\n";
                   dstMeansList << mean;
                }
            }
            qDebug() << "SRC:" << srcMsg << "yingbaio: " << phMsg << "DEST" << dstMeansList;
            emit sig_destWordMsg(size, dstMeansList, phMsg);
        }
    } else {
        return ;
    }
}
